<template>
  <div id="globalSider">
    <a-layout-sider
      v-if="loginUserStore.loginUser.id"
      class="sider"
      width="200"
      breakpoint="lg"
      :collapsed-width="0"
      :default-collapsed="true"
    >
      <a-menu
        mode="inline"
        v-model:selectedKeys="current"
        :items="menuItems"
        @click="doMenuClick"
      />
    </a-layout-sider>
  </div>
</template>
<script lang="ts" setup>
import {computed, h, ref, watchEffect} from 'vue'
import { HomeOutlined, TeamOutlined, RobotOutlined } from '@ant-design/icons-vue'
import { MenuProps, message } from 'ant-design-vue'
import { useRouter } from 'vue-router'
import { useLoginUserStore } from '@/stores/useLoginUserStore'
import { userLogoutUsingPost } from '@/api/userController'
import {SPACE_TYPE_ENUM} from "@/constants/space";
import {listMyTeamSpaceUsingPost} from "@/api/spaceUserController";

const loginUserStore = useLoginUserStore()

const router = useRouter() //获取路由对象
// 监听路由变化，更新当前选中菜单
const current = ref<string[]>([])
router.afterEach((to, from, next) => {
  current.value = [to.path]
})
//点击菜单栏跳转对应路径函数
const doMenuClick = ({ key }: { key: string }) => {
  router.push(key);
}

/**
 * 用户注销
 */
const doLogout = async () => {
  const res = await userLogoutUsingPost()
  console.log(res)
  // 如果注销，跳转到登录页面
  if (res.data.code === 0) {
    loginUserStore.setLoginUser({
      userName: '未登录',
    })
    message.success('退出登录成功')
    await router.push('/user/login')
  } else {
    message.error('退出登录失败' + res.data.message)
  }
}

/**
 * 菜单项逻辑(
 */
//原始菜单列表
const fixedMenuItems = [
  {
    key: '/',
    icon: () => h(HomeOutlined),
    label: '公共图库',
    title: '公共图库',
  },
  {
    key: '/my_space',
    icon: () => h(RobotOutlined),
    label: '我的空间',
    title: '我的空间',
  },
  {
    key: '/add_space?type=' + SPACE_TYPE_ENUM.TEAM,
    icon: () => h(TeamOutlined),
    label: '创建团队',
    title: '创建团队',
  },
]

/**
 * 团队空间列表展示
 */
const teamSpaceList = ref<API.SpaceUserVO[]>([]);
const menuItems = computed(() => {
  // 没有团队空间，只展示固定菜单
  if(teamSpaceList.value.length < 1) {
    return fixedMenuItems;
  }
  // 如果有团队空间，则增加团队空间菜单
  const teamSpaceSubMenus = teamSpaceList.value.map((spaceUser) => {
    const space = spaceUser.space;
    return {
      key: '/space/' + spaceUser.spaceId,
      label: space?.spaceName
    }
  })
  //我的团队分隔
  const teamSpaceMenuGroup = {
    type: 'group',
    label: '我的团队',
    key: 'teamSpace',
    children: teamSpaceSubMenus,
  }
  return [...fixedMenuItems, teamSpaceMenuGroup];
})

// 后端加载团队空间列表
const fetchTeamSpaceList = async () => {
  const res = await listMyTeamSpaceUsingPost();
  if(res.data.code === 0 && res.data.data) {
    teamSpaceList.value = res.data.data;
  } else {
    message.error('加载我的团队空间失败，' + res.data.message);
  }
}

/**
 * watch监听变量，如果有改动立即触发重新加载
 */
watchEffect(() => {
  // 只有用户登录才会加载
  if(loginUserStore.loginUser.id) {
    fetchTeamSpaceList();
  }
})

// 过滤菜单项
const filterMenus = (menus = [] as MenuProps['items']) => {
  return menus?.filter((menu) => {
    if (menu.key.startsWith('/admin')) {
      const loginUser = loginUserStore.loginUser
      if (!loginUser || loginUser.userRole !== 'admin') {
        return false
      }
    }
    return true
  })
}
// 通过过滤菜单方法过滤用户不需要看到的菜单项
const items = computed<MenuProps['items']>(() => filterMenus(originItems))
</script>
<style scoped>
#globalSider .sider {

}
</style>
